/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jfonia.view.labels;

import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import org.jfonia.connect5.basics.BasicValueNode;
import org.jfonia.connect5.basics.MutableValueNode;
import org.jfonia.connect5.basics.Observer;
import org.jfonia.connect5.relations.Equal;
import org.jfonia.constants.ViewConstants;
import org.jfonia.view.main.MainFrame;

/**
 *
 * @author Rik Bauwens
 */
public class LabelView extends JPanel implements MouseListener
{
        private Label label;
        private MutableValueNode<Double> widthNode;
        private Equal<Double> widthEqualRelation;

        public LabelView(Label label)
        {
                super();
                setBounds(0, 0, ViewConstants.LABEL_WIDTH, ViewConstants.LABELS_BAR_HEIGHT);
                setPreferredSize(new Dimension(ViewConstants.LABEL_WIDTH, ViewConstants.LABELS_BAR_HEIGHT));
                setBackground(ViewConstants.LABEL_COLOR);
                addMouseListener(this);
                widthNode = new BasicValueNode<Double>(0.0);
                this.label = label;
                label.getRatioNode().addObserver(new Observer()
                {
                        public void onNotify(Object source)
                        {
                                setPosition();
                        }
                });
                widthNode.addObserver(new Observer()
                {
                        public void onNotify(Object source)
                        {
                                setPosition();
                        }
                });
                setPosition();
        }

        public Label getLabel()
        {
                return label;
        }

        public void setWidthNode(MutableValueNode<Double> widthNode)
        {
                if(widthEqualRelation != null)
                        widthEqualRelation.switchOff();
                widthEqualRelation = new Equal<Double>(widthNode, this.widthNode);
                setPosition();
        }

        private void setPosition()
        {
                if(widthNode.getValue().compareTo(new Double(0.0)) != 0)
                        setLocation((int) (label.getRatio() * widthNode.getValue()), 0);
        }

        public void mouseClicked(MouseEvent e)
        {
                MainFrame.getInstance().scrollTo(label.getRatio());
        }

        public void mousePressed(MouseEvent e) {}

        public void mouseReleased(MouseEvent e) {}

        public void mouseEntered(MouseEvent e) {}

        public void mouseExited(MouseEvent e) {}
}
